<?php
require_once 'CMS/Util.php';
require_once 'CMS/Mvc/BaseController.php';
require_once 'CMS/Mvc/BaseUserController.php';
require_once 'CMS/UserCommon.php';
require_once 'CMS/User.php';
require_once 'CMS/Language.php'; //include thu vien language

class IndexController extends BaseUserController{

	public function init(){
		parent::init();
		$tbSetting = new User_Model_Parameter();
		$temp = $tbSetting->selectSetting("config");
		$layout = unserialize($temp[0]["parameter_value"]);
		if($layout['config_template'] !="")
		{
			$this->_helper->layout()->setLayout($layout['config_template']);
			$_SESSION['config_template'] = $layout['config_template'];
		}
		else
		{
			$this->_helper->layout()->setLayout('layoutmain');
			$_SESSION['config_template'] = 'layoutmain';
		}
	}

	public function indexAction(){
		$_SESSION['page_code'] = 'homepage';
		
		$tbSidebarModule = new User_Model_SidebarModule();
		$Modules = $tbSidebarModule->selectAllModule();
		foreach($Modules as $module)
		{
			$database_show_widget [] = $module["module_code"];
			$database_order_widget [$module["module_code"]] =  $module["sort_order"];
		}
		
		$tbDefaultbarModule = new User_Model_DefaultModuleToPage();
		$defaultModules = $tbDefaultbarModule->selectAllModule("homepage");
		foreach($defaultModules as $dmodule)
		{
			$content_show_widget [] = $dmodule["module_code"];
			$content_order_widget [$dmodule["module_code"]] =  $dmodule["sort_order"];
		}
		
		$tbContentbarModule = new User_Model_ContentModuleToPage();
		// mac dinh homepage
		$ContentModules = $tbContentbarModule->selectAllModule("homepage");	
		foreach($ContentModules as $cmodule)
		{
			$content_show_widget [] = $cmodule["module_code"];
			$content_order_widget [$cmodule["module_code"]] =  $cmodule["sort_order"];
		}	
		
		$front     = Zend_Controller_Front::getInstance();
		$widgets = $front->getPlugins();
	
		foreach($widgets as $widget)
		{
			if(count($Modules) > 0){
				if($widget->name !="" && in_array($widget->name, $database_show_widget))
				{
					$widget->enable = 1;
					$widget->order = $database_order_widget[$widget->name];
				}
			}
			if(count($content_show_widget) > 0){
				if($widget->name !="" && in_array($widget->name, $content_show_widget))
				{
						$widget->enable = 1;
						$widget->order = $content_order_widget[$widget->name];
				}	
			}	
		}
	}
	
	public function categoryAction(){
		
		$tbParameter = new User_Model_Parameter();
		$_SESSION['page_code'] = 'productcategory';
		$_GET['type'] = 1;
		
		//Start------get type show
		$code = "Show_".$_SESSION['page_code'];
		$pageshow = $tbParameter->selectSetting($code);
		//End--------get type show
		if(count($pageshow)>0)
		{
			$_GET['show'] = $pageshow[0]["parameter_value"];
		}
		else 
		{
			$_GET['show'] = 1;
		}
		
		$tbSidebarModule = new User_Model_SidebarModule();
		$Modules = $tbSidebarModule->selectAllModule();
		if($Modules!=null)
		{
		foreach($Modules as $module)
		{
			$database_show_widget [] = $module["module_code"];
			$database_order_widget [$module["module_code"]] =  $module["sort_order"];
		}
		}
		$tbDefaultbarModule = new User_Model_DefaultModuleToPage();
		$defaultModules = $tbDefaultbarModule->selectAllModule("productcategory");
		if($defaultModules!=null)
		{
		foreach($defaultModules as $dmodule)
		{
			$content_show_widget [] = $dmodule["module_code"];
			$content_order_widget [$dmodule["module_code"]] =  $dmodule["sort_order"];
		}
		}
		$tbContentbarModule = new User_Model_ContentModuleToPage();
		// mac dinh homepage
		$ContentModules = $tbContentbarModule->selectAllModule("productcategory");	
		if($ContentModules!=null)
		{
		foreach($ContentModules as $cmodule)
		{
			$content_show_widget [] = $cmodule["module_code"];
			$content_order_widget [$cmodule["module_code"]] =  $cmodule["sort_order"];
		}	
		}
		$front     = Zend_Controller_Front::getInstance();
		$widgets = $front->getPlugins();
	
		foreach($widgets as $widget)
		{
			if(count($Modules) > 0){
				if($widget->name !="" && in_array($widget->name, $database_show_widget))
				{
					$widget->enable = 1;
					$widget->order = $database_order_widget[$widget->name];
				}
			}
			if(count($content_show_widget) > 0){
				if($widget->name !="" && in_array($widget->name, $content_show_widget))
				{
						$widget->enable = 1;
						$widget->order = $content_order_widget[$widget->name];
				}	
			}		
		}
	}
	
	public function detailAction(){
		$_GET['type'] = 1;
		$_SESSION['page_code'] = 'productdetail';
		
		$tbSidebarModule = new User_Model_SidebarModule();
		$Modules = $tbSidebarModule->selectAllModule();
		foreach($Modules as $module)
		{
			$database_show_widget [] = $module["module_code"];
			$database_order_widget [$module["module_code"]] =  $module["sort_order"];
		}
		
		$tbDefaultbarModule = new User_Model_DefaultModuleToPage();
		$defaultModules = $tbDefaultbarModule->selectAllModule("productdetail");
		foreach($defaultModules as $dmodule)
		{
			$content_show_widget [] = $dmodule["module_code"];
			$content_order_widget [$dmodule["module_code"]] =  $dmodule["sort_order"];
		}
		
		$tbContentbarModule = new User_Model_ContentModuleToPage();
		// mac dinh homepage
		$ContentModules = $tbContentbarModule->selectAllModule("productdetail");	
		foreach($ContentModules as $cmodule)
		{
			$content_show_widget [] = $cmodule["module_code"];
			$content_order_widget [$cmodule["module_code"]] =  $cmodule["sort_order"];
		}	
		
		$front     = Zend_Controller_Front::getInstance();
		$widgets = $front->getPlugins();
	
		foreach($widgets as $widget)
		{
			if(count($Modules) > 0){
				if($widget->name !="" && in_array($widget->name, $database_show_widget))
				{
					$widget->enable = 1;
					$widget->order = $database_order_widget[$widget->name];
				}
			}
			if(count($content_show_widget) > 0){
				if($widget->name !="" && in_array($widget->name, $content_show_widget))
				{
						$widget->enable = 1;
						$widget->order = $content_order_widget[$widget->name];
				}	
			}			
		}
	}
	
	public function previewAction(){
		$this->_helper->layout->disableLayout();
		$preview_html = Util::html_editor();
		if($preview_html=="")
			$this->view->html = "Empty Content Page !!!";
		else 
			$this->view->html = $preview_html;
	}
	public function postAction(){
		$this->_helper->layout->disableLayout();
		$session = new Zend_Session_Namespace('login.auth');
		/*========== Start Load Language ==========*/
		$language = new Language(APPLICATION_PATH . '/modules/user/languages/product');
		if(isset($_SESSION['language']))
		{
			$language_id = $_SESSION['language'];
			$tbLanguage = new Language_Model_Language();
			$name = $tbLanguage->getNameLanguage($language_id);
			$language->load($name['name']);
		}
		else
			$language->load('Default');

		$languages = $tbLanguage->getAllLanguages();
		$this->view->languages = $languages;
		/*========== End Load Language ==========*/
			/*========== Start Get Text ==============*/
		$this->view->textTitle			= $language->get('text_title');
		$this->view->textProductName	= $language->get('text_ProductName');
		$this->view->textCate 			= $language->get('text_cate');
		$this->view->textImage			= $language->get('text_Image');
		$this->view->textChangeImage 	= $language->get('text_ChangeImage');
		$this->view->RelateImage 		= $language->get('text_RelateImage');
		$this->view->ButtonName			= $language->get('text_ButtonName');
		$this->view->Price				= $language->get('text_Price');
		$this->view->Productinfo		= $language->get('text_Productinfo');
		$this->view->ShortDes			= $language->get('text_ShortDes');
		$this->view->Save				= $language->get('text_Save');
		$this->view->textError1 		= $language->get('error1');
		$this->view->textError2 		= $language->get('error2');
		$this->view->textError3 		= $language->get('error3');
		$this->view->textError4 		= $language->get('error4');
		$this->view->textError5 		= $language->get('error5');
		$this->view->textError6 		= $language->get('error6');
		$this->view->textError7 		= $language->get('error7');
		$this->view->textError8 	= $language->get('error8');
		/*========== End Text ==============*/		

		
		//Test mac dinh dang nhap
		
		//$user = new User();
		//$user->login("california", "anhnhoem");
		
		//End - Test
		//Check permission
		$path = APPLICATION_PATH."/widgets/lastestproduct/";
		$xmlconfig = new SimpleXMLElement($path."config.xml",null,true);//Read config.xml
		$user = new User();
		$user->init();
		$user->check_login();
		$hasmodify = $user->modifiy_content($xmlconfig->name);
		if($hasmodify=="false")
		{
			$this->view->error = 8;
			return;
		}
		//End check permission
		
		/*if(!isset($_SESSION["id_user"]))
		{
			$this->view->error = 7;
		}*/
		if(isset($_SESSION["PostProduct_Error"]))
		{
			$this->view->error = $_SESSION["PostProduct_Error"];
			unset($_SESSION["PostProduct_Error"]);
		}
		if(isset($_GET["action"])&&($_GET["action"]=="new")&&(!isset($this->view->error)))
		{
			if(!isset($_POST["product_title"])||(strlen($_POST["product_title"])<5))
			{
				$this->view->error = 2;
				$this->view->error_title = 1;
			}
			if(!isset($_POST["product_category"])||(!is_numeric($_POST["product_category"]))||($_POST["product_category"]<=0))
			{
				$this->view->error = 3;
				$this->view->error_cate = 1;
			}
			$error_desc = array();
			
			//check default
			if(!isset($_POST["product_description"]['Default'])||(strlen($_POST["product_description"]['Default'])<20))
			{
				$this->view->error = 4;
				$error_desc['Default'][0] = $language->get('error4');
			}
			if(!isset($_POST["product_short_description"]['Default'])||(strlen($_POST["product_short_description"]['Default'])<10))
			{
				$this->view->error = 5;
				$error_desc['Default'][1] = $language->get('error5');
			}
			//check multi language			
			foreach($languages as $lang){
				if(!isset($_POST["product_description"][$lang['name']])||(strlen($_POST["product_description"][$lang['name']])<20))
				{
					$this->view->error = 4;
					$error_desc[$lang['name']][0] = $language->get('error4');
				}
				if(!isset($_POST["product_short_description"][$lang['name']])||(strlen($_POST["product_short_description"][$lang['name']])<10))
				{
					$this->view->error = 5;
					$error_desc[$lang['name']][1] = $language->get('error5');
				}
			}
			$this->view->error_desc = $error_desc;
			
			if(!isset($_POST["product_price"])||(!is_numeric($_POST["product_price"]))||($_POST["product_price"]<=1000))
			{
				$this->view->error = 6;
				$this->view->error_price = 1;
			}
		}
		//End--------Check Input Parameter
		
		//Start------Khai báo các parameter
		$tbcategory = new User_Model_Categories();
		$tbthings = new User_Model_Things();
		$tbimagetothing = new User_Model_ImageToThing();
		$dateInt = new Util();
		$tbuser = new User_Model_Users();
		//End--------Khai báo các parameter
		
		//Start------Check Input Parameter
			$session = new Zend_Session_Namespace('login.auth');
			if(!isset($session->id_user))
			{
				$this->view->error = 7;
			}
			else 
			{
				//Start------Get user
				$user = $tbuser->selectUser($session->id_user);
				//End--------Get user
			}
		//End--------Check Input Parameter
		
		//Start------Get Product Category
		if(isset($_GET['cate']))
		{
			$this->view->cate = $_GET['cate'];
			$CategoriesProduct = array();
		}
		else
		{
			$catetemp = $tbcategory->getLeafCategoriesbyType(1);
			$CategoriesProduct = array();
			if(isset($name['name']) && $name['name'] != '')
				$nL = $name['name'];
			else 
				$nL = 'Default';			
			foreach ($catetemp as $c_t){
				$t_c = unserialize($c_t['category_name']);
				if(!isset($t_c[$nL])){
					$nameCate = $t_c['Default'];
				}else{
					$nameCate = $t_c[$nL];
				}
				$CategoriesProduct[] = array(
												'category_id'	=> $c_t['category_id'],
												'category_name' => $nameCate
											);
			}

		}
		//End--------Get Product Category
		
		//Start------get catgory by id
		/*if(count($_GET) && isset($_GET["cate"]) && is_numeric($_GET["cate"]) && $_GET["cate"]>0) {
			$category_id = $_GET["cate"];
			$category = $tbcategory->getCategoriesbyId($category_id);
			//$this->view->category_name = $category[0]["category_name"];
			$this->view->category_id = $category[0]["category_id"];
			
			//Start------get name of category
			$nameCate = unserialize($category[0]['category_name']);
			if(isset($nameCate[$name['name']]) && isset($name)){
				$category_name = $nameCate[$name['name']];
			}else{
				$category_name = $nameCate['Default'];
			}
			$this->view->category_name = $category_name;
			//End--------get name of category
		}*/
		//End--------get catgory by id
		
		if(isset($_GET["action"])&&($_GET["action"]=="new")&&(!isset($this->view->error)))
		{
			
			foreach($_POST["product_description"] as $lang1 => $value)
			{
				$_POST["product_description"][$lang1]=str_replace(array('\\'),array(""),$value);
				//$_POST["product_description"][$lang1]=str_replace(array('<p>','</p>'),array(" "),$value);
				//print_r($_POST["product_description"][$lang1]);die;//cho nai moi replace ma bo'
			}
			
			$inserData = array(
								'category_id'	=>	$_POST["product_category"],
								'user_id'		=>	$session->id_user,
								'title'			=>	$_POST["product_title"],
								'common_info'	=>	serialize($_POST["product_description"]),//html_entity_decode($_POST["product_description"]),
								'short_description'	=>	serialize($_POST["product_short_description"]),
								'avatar'		=>	$_POST["product_avatar"],
								'price'			=>	$_POST["product_price"],
								'type'			=>	1,
								'views'			=>	0,
								'created_date'	=>	$dateInt->get_time_now(),
								'update_date'	=>	$dateInt->get_time_now(),
								'deleted'		=>	0
								);
			$result = $tbthings->insertThings($inserData);
			$things = $tbthings->getLastThingId();
			$thing_id = $things["maxId"];
			foreach ($_POST["image_related"] as $image)
			{
				if($image!="" && $image!=null)
				{
					$inserData = array(
										'thing_id' => $thing_id,
										'url' => $image
					);
					$result = $tbimagetothing->insertImageRelated($inserData);
				}
			}
			$this->view->error = $result;
		}
		if(isset($_POST["product_title"]))
		{
			$this->view->title = $_POST["product_title"];
		}
		else 
		{
			$this->view->title = "";
		}
		if(isset($_POST["product_short_description"]))
		{
			$this->view->short_des = $_POST["product_short_description"];
		}
		else 
		{
			$this->view->short_des = "";
		}
		if(isset($_POST["product_price"]))
		{
			$this->view->price = $_POST["product_price"];
		}
		else 
		{
			$this->view->price = "";
		}
		if(isset($_POST["product_category"]))
		{
			$this->view->category = $_POST["product_category"];
		}
		else 
		{
			$this->view->category = 0;
		}
		if(isset($_POST["product_description"]))
		{
			$this->view->description = $_POST["product_description"];
		}
		else 
		{
			$this->view->description = "";
		}
		//Start------Truyền parameter qua View
		if(count($CategoriesProduct)>0)
		{
			$this->view->CategoriesProduct = $CategoriesProduct;
		}
		else 
		{
			$this->view->CategoriesProduct = array();
		}
		//End--------Truyền parameter qua View
		
		
	}
	public function switchtypeshowAction(){
		$this->_helper->layout->disableLayout();
		if(count($_GET) && isset($_GET["typeshow"]) && is_numeric($_GET["typeshow"]) && $_GET["typeshow"]>0 && $_GET["typeshow"]<4) {
			
			$typeshow = $_GET["typeshow"];
			$data=array(
				'parameter_name' 	=> "Show_productcategory",
				'parameter_value' 	=> $typeshow
			);
			
			//Start------Khai báo các parameter
			$dbshow = new User_Model_Parameter();
			//End--------Khai báo các parameter
			
			//Start------Cập nhật phương thức hiển thị
			$result = $dbshow->updateSetting($data);
			//End--------Cập nhật phương thức hiển thị
			if(isset($_GET['category'])&&is_numeric($_GET["category"]) && $_GET["category"]>0)
			{
				$redirect = "/index/category?category=".$_GET['category'];
			}
			else 
			{
				$redirect = "/index/category";
			}
			$this->_redirect($redirect);
			print_r($redirect);
		}
		else {
			$this->_redirect("/index/category");
		}
	}
}